import { defineStore } from 'pinia'
import { ref } from 'vue'
import { computed } from 'vue'
import { useUserStore } from './user'
import { insertCartAPI, findNewCartAPI, delCartAPI } from '@/apis/cart'


export const useCartStore = defineStore('cart',() => {
    const userStore = useUserStore()

    const isLogin = computed(() => userStore.userInfo.token)
    const cartList = ref([])

    const upDateCartList = async () => {
        const res = await findNewCartAPI()
        cartList.value = res.data.result
    }
    const addCart = async (good) => {
        if ( isLogin.value ){
            // 用户登录了，进行登录操作
            const { skuId, count } = good
            await insertCartAPI({skuId, count})
            upDateCartList()
        }else{
            // 用户没登录，进行本地操作
            const item = cartList.value.find((item) => good.skuId === item.skuId)
            if(item){
                item.count++
            }else{
                cartList.value.push(good)
            }
        }
    }

    const clearList = async (skuId) => {
        if(isLogin.value){
            await delCartAPI([skuId])
            upDateCartList()
        }else{
            const index = cartList.value.findIndex((item) => item.skuId === skuId)
            cartList.value.splice(index, 1)
        }
    }

    const clearCart = () => {
        cartList.value = []
    }

    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    const selectCount = computed(() => cartList.value.filter((item) => item.select).reduce((a, c) => a + c.count, 0))
    const selectPrice = computed(() => cartList.value.filter((item) => item.select).reduce((a, c) => a + c.count * c.price, 0))

    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.select))

    // 单选功能
    const singleCheck = (i, select) => {
        const item = cartList.value.find((item) => i.skuId === item.skuId)
        item.select = select
    }

    // 全选功能
    const allCheck = (select) => {
        cartList.value.forEach((item) => item.select = select)
    }

    return {
        cartList,
        allCount,
        allPrice,
        isAll,
        selectCount,
        selectPrice,
        clearCart,
        addCart,
        clearList,
        singleCheck,
        allCheck,
        upDateCartList, //更新数据
    }
},{
    persist: true,
})